package com.example.baiduapi.Timmer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.*;
/**
 * 定时任务多线程并发
 * 所有的任务都在同一线程池但不同线程中完成
 */

/**
 * 定时任务多线程并发
 * 所有的任务都在同一个线程池但不同线程中完成
 */
@Configuration
public class ScheduleConfig implements SchedulingConfigurer {

    @Autowired
    ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.setScheduler(Executors.newScheduledThreadPool(8,threadPoolTaskExecutor));
    }


    // 实时开始/取消定时器
    private static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    private int time = 0;
    private static ConcurrentHashMap<String , ScheduledFuture<?>> futureMap = new ConcurrentHashMap();

    public static void main(String[] args) {
        ScheduleConfig scheduleConfig = new ScheduleConfig();
        scheduleConfig.fetchAndScheduleRefresh();
    }

    public void fetchAndScheduleRefresh(){
        System.out.println("开始执行"+time);
        time = time + 1;

        if (time >= 5) {
            System.out.println("达到5，取消定时器");
            if (futureMap.get("fetchAndScheduleRefresh") != null) {
                futureMap.get("fetchAndScheduleRefresh").cancel(false); // 取消定时任务
            }
            scheduler.shutdown(); // 可选，关闭线程池
            return;
        }

        futureMap.put("fetchAndScheduleRefresh",scheduler.schedule(this::fetchAndScheduleRefresh, 3, TimeUnit.SECONDS));
    }
}
